package com.llkj.qingnianguoxue.album;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.llkj.qingnianguoxue.R;

import java.io.File;
import java.io.FilenameFilter;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

/***
 * * @description
 * * 由 马君 创建于 2015年11月28日 19:15
 ***/
public class LocalImageShower extends RelativeLayout implements View.OnClickListener,AdapterView.OnItemClickListener{

    public static final int MAX=-1;
    public static final int MESSAGE_NEWEST_FINISH=0x04;     //最新的照片被扫描到的消息
    public static final int MESSAGE_ALL_FINISH=0x08;        //所有照片扫描结束的消息
    public static final int MESSAGE_ALBUM=0x10;             //当前相册所有图片查询结束的消息

    private int infoHeight=45;                  //相册信息栏高度，单位dp
    private int infoBgColor=0xCC000000;         //相册信息栏背景颜色
    private int infoPaddingLeft=10;             //相册信息栏左padding
    private int infoPaddingRight=10;            //相册信息栏右padding
    private int infoNameTextSize=16;            //相册名的文字大小
    private int infoNameTextColor=0xffffffff;   //相册名的颜色
    private int infoTextSize=14;                //相册信息的文字大小

    private int columns=3;                      //图片显示时，每排的个数

    private Bitmap imageNoChecked;              //图片未被选中时的右上角图标
    private Bitmap imageChecked;                //图片被选中时的右上角图标

    private String newestNickName="最新图片";   //《最近的》图集显示名称

    private int newestSize=100;                 //《最近的》图集包含的图片数
    private int maxSelectedSize=9;              //最多选取图片张数

    private int imageSize;                      //计算得到的每个ImageView的大小
    private int flagImageSize;                  //计算得到的ImageView选择标志的大小

    private RelativeLayout infoContainer;       //相册信息栏View
    private TextView nowAlbumsTv;               //当前相册名显示View
    private TextView infoTv;                    //相册信息VIew

    private ListView albumsListView;            //相册列表
    private AlbumListAdapter albumAdapter;      //相册列表的适配器

    private DisplayMetrics metrics;             //屏幕信息

    private List<ImageFolder> albums;
    private List<String> newestImg;

    private Context context;
    private int screenHeight;

    private GridView gView;                     //图片显示的GridView
    private List<String> data;                  //当前显示的图片文件夹中的图片集合
    private ArrayList<String> selectedImgs;     //选中的图片集合
    private ImageAdapter imageAdapter;          //图片显示的Adapter

    private int bgColor=0xffDDDDDD;
    private int itemBgColor=0xffffffff;
    private int space=3;


    private ImageFolder imageFolder;            //当前的图片文件夹

    public LocalImageShower(Context context) {
        this(context, null);
    }

    public LocalImageShower(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public LocalImageShower(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    public LocalImageShower(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        init();
    }

    public void init(){
        context=getContext();
        setBackgroundColor(0xffDDDDDD);
        initDefaultData();
        initView();
        initEvent();
        getAlbums();
    }

    public void initDefaultData(){
        metrics=new DisplayMetrics();
        ((Activity)context).getWindowManager().getDefaultDisplay().getMetrics(metrics);
        screenHeight=metrics.heightPixels;
        albums=new ArrayList<>();
        selectedImgs=new ArrayList<>();
    }

    public void initView(){
        createAlbumListView();
        createInfoView();
        createImageGridView();
        albumListWindow = new AlbumListWindow(albumsListView, LayoutParams.MATCH_PARENT, (int) (screenHeight*0.6f));
        this.addView(gView);
        this.addView(infoContainer);
    }

    public void initEvent(){
        albumsListView.setOnItemClickListener(this);
        gView.setOnItemClickListener(this);
    }

    public void setSelectedImages(ArrayList<String> list){
        this.selectedImgs=list;
    }

    public void setMaxSelectedSize(int maxSelectedSize){
        this.maxSelectedSize=maxSelectedSize;
    }

    public void setNewestNickName(String newestNickName){
        this.newestNickName=newestNickName;
    }

    public void setColumns(int columns){
        this.columns=columns;
        if(gView!=null){
            gView.setNumColumns(columns);
        }
    }

    public ArrayList<String> getSelectedImgs(){
        return selectedImgs;
    }

    /**
     * 选择当前选择的相册
     * @param folder 要展示的相册
     */
    private void setAlbum(final ImageFolder folder){
        new Thread(new Runnable() {
            @Override
            public void run() {
                if(data==null){
                    data=new ArrayList<>();
                }else{
                    data.clear();
                }
                imageFolder=folder;
                ContentResolver resolver=context.getContentResolver();
                Cursor cursor;
                if(folder==null||folder.getDir()==null||folder.getDir().length()==0){
                    cursor=resolver.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                            new String[]{
                                    MediaStore.Images.Media.DATA,
                                    MediaStore.Images.Media.DISPLAY_NAME,
                                    MediaStore.Images.Media.DATE_MODIFIED
                            },
                            MediaStore.Images.Media.MIME_TYPE + "=? or "
                                    + MediaStore.Images.Media.MIME_TYPE + "=? or "
                                    + MediaStore.Images.Media.MIME_TYPE + "=?",
                            new String[] { "image/jpeg", "image/png","image/jpg"},
                            MediaStore.Images.Media.DATE_MODIFIED+" desc"+(newestSize<0?"":(" limit "+newestSize)));
                }else{
                    cursor=resolver.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                            new String[]{
                                    MediaStore.Images.Media.DATA,
                                    MediaStore.Images.Media.DISPLAY_NAME,
                                    MediaStore.Images.Media.DATE_MODIFIED
                            },
                            MediaStore.Images.ImageColumns.BUCKET_ID+"=? and ("+
                                    MediaStore.Images.Media.MIME_TYPE + "=? or "
                                    + MediaStore.Images.Media.MIME_TYPE + "=? or "
                                    + MediaStore.Images.Media.MIME_TYPE + "=?) ",
                            new String[] { folder.getId(),"image/jpeg", "image/png","image/jpg"},
                            MediaStore.Images.Media.DATE_MODIFIED+" desc");
                }
                if(cursor==null)return;
                while(cursor.moveToNext()){
                    data.add(cursor.getString(0));
                }
                cursor.close();
                handler.sendEmptyMessage(MESSAGE_ALBUM);
            }
        }).start();
    }

    private void refreshAlbumListView(){
        albumAdapter=new AlbumListAdapter(albums);
        albumsListView.setAdapter(albumAdapter);
    }

    public boolean checkImageChoose(){
        if(selectedImgs.size()>=maxSelectedSize){
            Toast.makeText(context, "最多只能选" + maxSelectedSize + "张", Toast.LENGTH_SHORT).show();
            return false;
        }
        return true;
    }

    private void refreshImageShower(ImageFolder imageFolder){
        setAlbum(imageFolder);
        nowAlbumsTv.setText(imageFolder.getName()+"("+imageFolder.getCount() + ")" + "▶");
        infoTv.setText("已选:"+selectedImgs.size()+"/"+maxSelectedSize);
    }

    /**
     * 将dp转换为px
     * @param context
     * @param dpValue   传入的dp值
     * @return px值
     */
    private int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    /**
     * 另外开线程获取相册集合
     */
    private void getAlbums(){
        if(albums==null){
            albums=new ArrayList<>();
        }
        new Thread(new Runnable() {
            @Override
            public void run() {
                albums.clear();

                //最新相册单独生成，并加入相册列表
                newestImg=getNewestPhotos(newestSize);
                ImageFolder newestFolder=new ImageFolder();
                newestFolder.setName(newestNickName);
                if(newestImg==null){
                	newestImg = new ArrayList<String>();
                }
                newestFolder.setCount(newestImg.size());
                if(newestImg.size()>0){
                    newestFolder.setFirstImagePath(newestImg.get(0));
                }
                albums.add(newestFolder);
                handler.sendEmptyMessage(MESSAGE_NEWEST_FINISH);     //通知主线程最新的相册已经生成

                //利用ContentResolver查询数据库，找出所有包含图片的文件夹，保存到相册列表中
                ContentResolver resolver=context.getContentResolver();
                Cursor cursor=resolver.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                        new String[]{
                                MediaStore.Images.Media.DATA,
                                MediaStore.Images.ImageColumns.BUCKET_ID,
                                MediaStore.Images.Media.DATE_MODIFIED,
                                "count(*) as count"
                        },
                        MediaStore.Images.Media.MIME_TYPE + "=? or "+
                                MediaStore.Images.Media.MIME_TYPE + "=? or "+
                                MediaStore.Images.Media.MIME_TYPE+"=?) " +
                                "group by ("+ MediaStore.Images.ImageColumns.BUCKET_ID,
                        new String[] { "image/jpeg", "image/png","image/jpg" },
                        MediaStore.Images.Media.DATE_MODIFIED+" desc");
                if(cursor==null)return;
                while(cursor.moveToNext()){
                    File file=new File(cursor.getString(0));
                    ImageFolder imageFolder=new ImageFolder();
                    imageFolder.setDir(file.getParent());
                    imageFolder.setId(cursor.getString(1));
                    imageFolder.setFirstImagePath(cursor.getString(0));
                    try{

                        imageFolder.setCount(file.getParentFile().list(new FilenameFilter() {
                            @Override
                            public boolean accept(File dir, String filename) {
                                return (filename.endsWith(".png") || filename.endsWith(".jpg") || filename.endsWith("jpeg"));
                            }
                        }).length);
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                    albums.add(imageFolder);
                }
                cursor.close();

                handler.sendEmptyMessage(MESSAGE_ALL_FINISH);
            }
        }).start();
    }

    /**
     * 获取《最新的》图片集合
     * @param size  图片集合包含的最大图片数
     * @return  图片集合
     */
    public ArrayList<String> getNewestPhotos(int size){
        ArrayList<String> imageBeans=new ArrayList<>();
        ContentResolver resolver=context.getContentResolver();
        Cursor cursor=resolver.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                new String[]{
                        MediaStore.Images.Media.DATA,
                        MediaStore.Images.Media.DISPLAY_NAME,
                        MediaStore.Images.Media.DATE_MODIFIED
                },
                MediaStore.Images.Media.MIME_TYPE + "=? or "
                        + MediaStore.Images.Media.MIME_TYPE + "=? or "
                        + MediaStore.Images.Media.MIME_TYPE + "=?",
                new String[] { "image/jpeg", "image/png","image/jpg"},
                MediaStore.Images.Media.DATE_MODIFIED+" desc"+(size<0?"":(" limit "+size)));
        if(cursor==null)return null;
        while(cursor.moveToNext()){
            imageBeans.add(cursor.getString(0));
        }
        cursor.close();
        return imageBeans;
    }

    public void switchAlbumWindow(){
        if(albumListWindow.isShowing()){
            albumListWindow.dismiss();
        }else{
            albumListWindow.showAsDropDown(infoContainer,0,0);
            // 设置背景颜色变暗
            WindowManager.LayoutParams lp = ((Activity)context).getWindow().getAttributes();
            lp.alpha = 0.5f;
            ((Activity)context).getWindow().setAttributes(lp);
        }
    }

    @Override
    public void onClick(View v) {
        if(v.equals(nowAlbumsTv)){
                albumListWindow.showAsDropDown(infoContainer,0,0);
                // 设置背景颜色变暗
                WindowManager.LayoutParams lp = ((Activity)context).getWindow().getAttributes();
                lp.alpha = 0.5f;
                ((Activity)context).getWindow().setAttributes(lp);
        }else if(v.equals(infoTv)){

        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        if(parent==albumsListView){
            albumListWindow.dismiss();
            WindowManager.LayoutParams lp = ((Activity)context).getWindow().getAttributes();
            lp.alpha = 1f;
            ((Activity)context).getWindow().setAttributes(lp);
            refreshImageShower(albums.get(position));
        }else if(parent==gView){
            if(!(data==null||position<0||position>=data.size())) {
                if(selectedImgs.contains(data.get(position))){
                    selectedImgs.remove(data.get(position));
                    ((SquareImageView) view).selectedReverse();
                }else{
                    if(checkImageChoose()){
                        ((SquareImageView) view).selectedReverse();
                        selectedImgs.add(data.get(position));
                    }
                }
                infoTv.setText("已选:"+selectedImgs.size()+"/"+maxSelectedSize);
            }
        }
    }

    //弱引用，以防止内存泄露
    private LocalImageShowerHandler handler=new LocalImageShowerHandler(this);
    private static class LocalImageShowerHandler extends Handler {

        WeakReference<LocalImageShower> shower;

        public LocalImageShowerHandler(LocalImageShower shower) {
            this.shower=new WeakReference<>(shower);
        }

        @Override
        public void handleMessage(Message msg) {
            LocalImageShower uthis=shower.get();
            switch (msg.what){
                case MESSAGE_ALBUM:
                    if(uthis.imageAdapter==null){
                        uthis.imageAdapter=uthis.new ImageAdapter(uthis.data);
                        uthis.gView.setAdapter(uthis.imageAdapter);
                    }
                    uthis.imageAdapter.notifyDataSetChanged();
                    break;
                case MESSAGE_NEWEST_FINISH:
                    uthis.refreshImageShower(uthis.albums.get(0));
                    break;
                case MESSAGE_ALL_FINISH:
                    uthis.refreshAlbumListView();
                    break;
            }
        }
    }

    /**
     * 显示相册的PopupWindow
     */
    private class AlbumListWindow extends PopupWindow {

        public AlbumListWindow(View contentView, int width, int height) {
            super(contentView, width, height);
            setBackgroundDrawable(new ColorDrawable(0));
            setTouchable(true);
            setOutsideTouchable(true);
            setFocusable(true);
            setTouchInterceptor(new OnTouchListener() {
                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    if (event.getAction() == MotionEvent.ACTION_OUTSIDE) {
                        dismiss();
                        return true;
                    }
                    return false;
                }
            });
            setOnDismissListener(new OnDismissListener() {
                @Override
                public void onDismiss() {
                    WindowManager.LayoutParams lp = ((Activity) context).getWindow().getAttributes();
                    lp.alpha = 1f;
                    ((Activity) context).getWindow().setAttributes(lp);
                }
            });
            setAnimationStyle(android.R.style.Animation_InputMethod);
            init();
        }

        private void init(){

        }

    }
    private AlbumListWindow albumListWindow;

    /**
     * 显示相册的ListView的Adapter
     */
    private class AlbumListAdapter extends BaseAdapter {

        private List<ImageFolder> data;

        public AlbumListAdapter(List<ImageFolder> data) {
            this.data = data;
        }

        @Override
        public int getCount() {
            return data==null?0:data.size();
        }

        @Override
        public Object getItem(int position) {
            return data.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ImageFolder imageFolder=data.get(position);
            if(convertView==null){
                ViewGroup view=new RelativeLayout(context);
                AbsListView.LayoutParams rootParams=new AbsListView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,dip2px(context, 80));
                view.setLayoutParams(rootParams);
                view.setPadding(dip2px(context, 10), 0, dip2px(context, 10), 0);
                ImageView iv=new ImageView(context);
                LayoutParams ivParams=new LayoutParams(dip2px(context, 60),dip2px(context, 60));
                ivParams.addRule(CENTER_VERTICAL);
                iv.setLayoutParams(ivParams);
                iv.setScaleType(ImageView.ScaleType.CENTER_CROP);

                view.addView(iv);

                TextView tv=new TextView(context);
                LayoutParams tvParams=new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
                tvParams.addRule(CENTER_VERTICAL);
                tvParams.addRule(RelativeLayout.RIGHT_OF,iv.getId());
                tv.setLayoutParams(tvParams);
                tv.setTextSize(16);
                tv.setTextColor(0xff2b2b2b);
                tv.setPadding(dip2px(context,10),0,dip2px(context,10),0);
                view.addView(tv);

                convertView=view;
                ViewHolder holder=new ViewHolder();
                holder.tv=tv;
                holder.iv=iv;
                convertView.setTag(holder);
            }

            ViewHolder holder= (ViewHolder) convertView.getTag();
//            ImageLoader.getInstance(3, ImageLoader.Type.LIFO).loadImage(imageFolder.getFirstImagePath(), holder.iv);
            Glide.with(context).load(imageFolder.getFirstImagePath()).error(R.drawable.default_pino).dontAnimate()
                    .into(holder.iv);
            holder.tv.setText(imageFolder.getName() + "(" + imageFolder.getCount() + ")");

            return convertView;
        }

        private class ViewHolder{
            public TextView tv;
            public ImageView iv;
        }
    }

    /**
     * 显示图片的GridView的Adapter
     */
    private class ImageAdapter extends BaseAdapter {

        private List<String> iData;

        public ImageAdapter(List<String> idata){
            this.iData=idata;
        }

        @Override
        public int getCount() {
            return iData==null?0:iData.size();
        }

        @Override
        public Object getItem(int position) {
            return iData.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            SquareImageView squareImageView;
            if(convertView==null){
                squareImageView=new SquareImageView(context);
                squareImageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
                squareImageView.setBackgroundColor(itemBgColor);
            }else{
                squareImageView= (SquareImageView) convertView;
            }
            String addr=iData.get(position);
//            squareImageView.setTag(0x0F000012, addr);
            if(selectedImgs.contains(addr)){
                squareImageView.selected(true);
            }else{
                squareImageView.selected(false);
            }
//            ImageLoader.getInstance(3, ImageLoader.Type.LIFO).loadImage(addr, squareImageView);
            Glide.with(context).load(addr).error(R.drawable.default_pino).dontAnimate()
                    .into(squareImageView);
            return squareImageView;
        }

    }

    public static class ImageFolder{

        private String dir;					//文件路径
        private String firstImagePath;		//第一张图片的路径
        private String name;				//文件夹显示名称
        private int count;					//图片的数量
        private String id;					//文件夹在数据库中的id

        public void setId(String id){
            this.id=id;
        }

        public String getId(){
            return id;
        }

        public String getDir(){
            return dir;
        }

        public void setDir(String dir){
            this.dir = dir;
            int lastIndexOf = this.dir.lastIndexOf("/");
            this.name = this.dir.substring(lastIndexOf+1);
        }

        public void setName(String name){
            this.name=name;
        }

        public String getFirstImagePath(){
            return firstImagePath;
        }

        public void setFirstImagePath(String firstImagePath){
            this.firstImagePath = firstImagePath;
        }

        public String getName(){
            return name;
        }

        public int getCount(){
            return count;
        }

        public void setCount(int count){
            this.count = count;
        }

    }

    //————————————For default setting—————————————————————————

    /**
     * 代码创建相册信息栏的布局
     */
    private void createInfoView(){
        infoContainer=new RelativeLayout(context);
        LayoutParams params=new LayoutParams(LayoutParams.MATCH_PARENT,dip2px(context,infoHeight));
        params.addRule(ALIGN_PARENT_BOTTOM);
        infoContainer.setLayoutParams(params);
        infoContainer.setBackgroundColor(infoBgColor);
        infoContainer.setPadding(dip2px(context, infoPaddingLeft), 0, dip2px(context, infoPaddingRight), 0);
        infoContainer.setClickable(true);

        nowAlbumsTv=new TextView(context);
        LayoutParams paramsNameTv=new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        paramsNameTv.addRule(CENTER_VERTICAL);
        nowAlbumsTv.setLayoutParams(paramsNameTv);
        nowAlbumsTv.setTextSize(infoNameTextSize);
        nowAlbumsTv.setTextColor(infoNameTextColor);
        nowAlbumsTv.setOnClickListener(this);
        nowAlbumsTv.setMinimumWidth(dip2px(context, 120));
        infoContainer.addView(nowAlbumsTv);

        infoTv=new TextView(context);
        LayoutParams paramsInfoTv=new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        paramsInfoTv.addRule(CENTER_VERTICAL);
        paramsInfoTv.addRule(ALIGN_PARENT_RIGHT);
        infoTv.setLayoutParams(paramsInfoTv);
        infoTv.setTextSize(infoTextSize);
        infoTv.setTextColor(infoNameTextColor);
        infoTv.setOnClickListener(this);
        infoContainer.addView(infoTv);
    }

    /**
     * 代码创建相册显示的ListView
     */
    public void createAlbumListView(){
        albumsListView=new ListView(context);
        albumsListView.setLayoutParams(new ViewGroup.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT));
        albumsListView.setBackgroundColor(0xffffffff);
        albumsListView.setPadding(0, dip2px(context, 10), 0, dip2px(context, 10));
    }

    public void createImageGridView(){
        gView=new GridView(context);
        gView.setNumColumns(columns);
        gView.setBackgroundColor(bgColor);
        gView.setHorizontalSpacing(space);
        gView.setVerticalSpacing(space);
        gView.setVerticalScrollBarEnabled(false);
    }

}
